# db_connector.py
import mysql.connector

class MySQLConnector:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None

    def connect(self):
        try:
            self.connection = mysql.connector.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database
            )
            if self.connection.is_connected():
                print(f"Connected to MySQL database '{self.database}'")
        except mysql.connector.Error as e:
            print(f"Error: {e}")

    def disconnect(self):
        if self.connection.is_connected():
            self.connection.close()
            print("Disconnected from MySQL database")

    def execute_query(self, query):
        cursor = self.connection.cursor()
        try:
            cursor.execute(query)
            return cursor.fetchall()
        finally:
            cursor.close()
    
    def execute(self, query, data=None):
        cursor = self.connection.cursor()
        try:
            if data:
                cursor.execute(query, data)
            else:
                cursor.execute(query)
            self.connection.commit()
        finally:
            cursor.close()

# 创建 MySQL 连接器实例
# connector = MySQLConnector(host='106.60.78.185', user='dh-wy-catalog', password='FjFtC3ADewiwBJKk', database='dh-wy-catalog')
connector = MySQLConnector(host='182.244.4.255', user='root', password='dx1q2w#E$R', database='dh-wy-catalog')

# 连接到数据库
connector.connect()
# connector.disconnect()
# connector.close()
